using SheLife.Application.Interfaces;
using SheLife.Domain.Entities;
using SheLife.Infrastructure.Repositories;
using SheLife.Domain.Interfaces;
using SheLife.Domain.Interfaces.Repositories;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SheLife.Application.Services
{
    /// <summary>
    /// 系统配置服务实现
    /// </summary>
    public class SystemConfigService : ISystemConfigService
    {
        private readonly IUnitOfWork _unitOfWork;

        public SystemConfigService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public async Task<SystemConfig?> GetSystemConfigByIdAsync(Guid id)
        {
            return await _unitOfWork.SystemConfigRepository.GetByIdAsync(id);
        }

        public async Task<SystemConfig?> GetSystemConfigByKeyAsync(string key)
        {
            return await _unitOfWork.SystemConfigRepository.GetByKeyAsync(key);
        }

        public async Task<IEnumerable<SystemConfig>> GetAllSystemConfigsAsync()
        {
            return await _unitOfWork.SystemConfigRepository.GetAllAsync();
        }

        public async Task<SystemConfig> CreateSystemConfigAsync(string key, string value, string? description = null, string? category = null)
        {
            var systemConfig = new SystemConfig
            {
                Id = Guid.NewGuid(),
                Key = key,
                Value = value,
                Description = description,
                Category = category,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _unitOfWork.SystemConfigRepository.AddAsync(systemConfig);
            await _unitOfWork.SaveChangesAsync();

            return systemConfig;
        }

        public async Task<SystemConfig?> UpdateSystemConfigAsync(Guid id, string? value, string? description, string? category)
        {
            var systemConfig = await _unitOfWork.SystemConfigRepository.GetByIdAsync(id);
            if (systemConfig == null)
                return null;

            if (value != null) systemConfig.Value = value;
            if (description != null) systemConfig.Description = description;
            if (category != null) systemConfig.Category = category;

            systemConfig.UpdatedAt = DateTime.UtcNow;

            await _unitOfWork.SystemConfigRepository.UpdateAsync(systemConfig);
            await _unitOfWork.SaveChangesAsync();

            return systemConfig;
        }

        public async Task<bool> DeleteSystemConfigAsync(Guid id)
        {
            var systemConfig = await _unitOfWork.SystemConfigRepository.GetByIdAsync(id);
            if (systemConfig == null)
                return false;

            await _unitOfWork.SystemConfigRepository.DeleteAsync(systemConfig);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<Dictionary<string, string>> GetSystemConfigsByCategoryAsync(string category)
        {
            var configs = await _unitOfWork.SystemConfigRepository.GetByCategoryAsync(category);
            return configs.ToDictionary(c => c.Key, c => c.Value);
        }
    }

    /// <summary>
    /// 系统日志服务实现
    /// </summary>
    public class SystemLogService : ISystemLogService
    {
        private readonly IUnitOfWork _unitOfWork;

        public SystemLogService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public async Task<SystemLog?> GetSystemLogByIdAsync(Guid id)
        {
            return await _unitOfWork.SystemLogRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<SystemLog>> GetSystemLogsByLevelAsync(string level, int page = 1, int pageSize = 20)
        {
            return await _unitOfWork.SystemLogRepository.GetByLevelPagedAsync(level, page, pageSize);
        }

        public async Task<IEnumerable<SystemLog>> GetSystemLogsByCategoryAsync(string category, int page = 1, int pageSize = 20)
        {
            return await _unitOfWork.SystemLogRepository.GetByCategoryPagedAsync(category, page, pageSize);
        }

        public async Task<IEnumerable<SystemLog>> GetSystemLogsByUserIdAsync(Guid userId, int page = 1, int pageSize = 20)
        {
            return await _unitOfWork.SystemLogRepository.GetByUserIdPagedAsync(userId, page, pageSize);
        }

        public async Task<IEnumerable<SystemLog>> GetSystemLogsByDateRangeAsync(DateTime startDate, DateTime endDate, int page = 1, int pageSize = 20)
        {
            return await _unitOfWork.SystemLogRepository.GetByDateRangePagedAsync(startDate, endDate, page, pageSize);
        }

        public async Task<SystemLog> CreateSystemLogAsync(string level, string category, string message, Guid? userId = null, string? details = null)
        {
            var systemLog = new SystemLog
            {
                Id = Guid.NewGuid(),
                Level = level,
                Category = category,
                Message = message,
                UserId = userId,
                Details = details,
                CreatedAt = DateTime.UtcNow
            };

            await _unitOfWork.SystemLogRepository.AddAsync(systemLog);
            await _unitOfWork.SaveChangesAsync();

            return systemLog;
        }

        public async Task<bool> DeleteSystemLogAsync(Guid id)
        {
            var systemLog = await _unitOfWork.SystemLogRepository.GetByIdAsync(id);
            if (systemLog == null)
                return false;

            await _unitOfWork.SystemLogRepository.DeleteAsync(systemLog);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> DeleteSystemLogsByDateRangeAsync(DateTime startDate, DateTime endDate)
        {
            var logs = await _unitOfWork.SystemLogRepository.GetByDateRangeAsync(startDate, endDate);
            foreach (var log in logs)
            {
                await _unitOfWork.SystemLogRepository.DeleteAsync(log);
            }

            await _unitOfWork.SaveChangesAsync();
            return true;
        }

        public async Task<Dictionary<string, object>> GetSystemLogStatisticsAsync(int days = 30)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-days);

            var logs = await _unitOfWork.SystemLogRepository.GetByDateRangeAsync(startDate, endDate);

            var statistics = new Dictionary<string, object>
            {
                ["TotalLogs"] = logs.Count(),
                ["LogsByLevel"] = logs.GroupBy(l => l.Level)
                                     .ToDictionary(g => g.Key, g => g.Count()),
                ["LogsByCategory"] = logs.GroupBy(l => l.Category)
                                       .ToDictionary(g => g.Key, g => g.Count()),
                ["DailyLogs"] = logs.GroupBy(l => l.CreatedAt.Date)
                                   .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count())
            };

            return statistics;
        }
    }

    /// <summary>
    /// 系统通知服务实现
    /// </summary>
    public class SystemNotificationService : ISystemNotificationService
    {
        private readonly ISystemNotificationRepository _systemNotificationRepository;
        private readonly IUnitOfWork _unitOfWork;

        public SystemNotificationService(ISystemNotificationRepository systemNotificationRepository, IUnitOfWork unitOfWork)
        {
            _systemNotificationRepository = systemNotificationRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<SystemNotification?> GetSystemNotificationByIdAsync(Guid id)
        {
            return await _systemNotificationRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<SystemNotification>> GetSystemNotificationsByUserIdAsync(Guid userId, int page = 1, int pageSize = 20)
        {
            return await _systemNotificationRepository.GetByUserIdPagedAsync(userId, page, pageSize);
        }

        public async Task<IEnumerable<SystemNotification>> GetUnreadSystemNotificationsByUserIdAsync(Guid userId, int page = 1, int pageSize = 20)
        {
            return await _systemNotificationRepository.GetUnreadByUserIdPagedAsync(userId, page, pageSize);
        }

        public async Task<IEnumerable<SystemNotification>> GetSystemNotificationsByTypeAsync(string type, int page = 1, int pageSize = 20)
        {
            return await _systemNotificationRepository.GetByTypePagedAsync(type, page, pageSize);
        }

        public async Task<SystemNotification> CreateSystemNotificationAsync(Guid userId, string type, string title, string content, string? actionUrl = null)
        {
            var systemNotification = new SystemNotification
            {
                Id = Guid.NewGuid(),
                UserId = userId,
                Type = type,
                Title = title,
                Content = content,
                ActionUrl = actionUrl,
                IsRead = false,
                CreatedAt = DateTime.UtcNow
            };

            await _systemNotificationRepository.AddAsync(systemNotification);
            await _unitOfWork.SaveChangesAsync();

            return systemNotification;
        }

        public async Task<SystemNotification?> UpdateSystemNotificationAsync(Guid id, string? title, string? content, string? actionUrl)
        {
            var systemNotification = await _systemNotificationRepository.GetByIdAsync(id);
            if (systemNotification == null)
                return null;

            if (title != null) systemNotification.Title = title;
            if (content != null) systemNotification.Content = content;
            if (actionUrl != null) systemNotification.ActionUrl = actionUrl;

            await _systemNotificationRepository.UpdateAsync(systemNotification);
            await _unitOfWork.SaveChangesAsync();

            return systemNotification;
        }

        public async Task<bool> DeleteSystemNotificationAsync(Guid id)
        {
            var systemNotification = await _systemNotificationRepository.GetByIdAsync(id);
            if (systemNotification == null)
                return false;

            await _systemNotificationRepository.DeleteAsync(systemNotification);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> MarkSystemNotificationAsReadAsync(Guid id)
        {
            var systemNotification = await _systemNotificationRepository.GetByIdAsync(id);
            if (systemNotification == null)
                return false;

            systemNotification.IsRead = true;
            systemNotification.ReadAt = DateTime.UtcNow;

            await _systemNotificationRepository.UpdateAsync(systemNotification);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> MarkAllSystemNotificationsAsReadAsync(Guid userId)
        {
            var notifications = await _systemNotificationRepository.GetUnreadByUserIdAsync(userId);
            foreach (var notification in notifications)
            {
                notification.IsRead = true;
                notification.ReadAt = DateTime.UtcNow;
                await _systemNotificationRepository.UpdateAsync(notification);
            }

            await _unitOfWork.SaveChangesAsync();
            return true;
        }

        public async Task<int> GetUnreadSystemNotificationCountAsync(Guid userId)
        {
            return await _systemNotificationRepository.GetUnreadCountByUserIdAsync(userId);
        }
    }

    /// <summary>
    /// 系统任务服务实现
    /// </summary>
    public class SystemTaskService : ISystemTaskService
    {
        private readonly ISystemTaskRepository _systemTaskRepository;
        private readonly IUnitOfWork _unitOfWork;

        public SystemTaskService(ISystemTaskRepository systemTaskRepository, IUnitOfWork unitOfWork)
        {
            _systemTaskRepository = systemTaskRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<SystemTask?> GetSystemTaskByIdAsync(Guid id)
        {
            return await _systemTaskRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<SystemTask>> GetAllSystemTasksAsync(int page = 1, int pageSize = 20)
        {
            return await _systemTaskRepository.GetAllPagedAsync(page, pageSize);
        }

        public async Task<IEnumerable<SystemTask>> GetPendingSystemTasksAsync(int page = 1, int pageSize = 20)
        {
            return await _systemTaskRepository.GetByStatusPagedAsync("待执行", page, pageSize);
        }

        public async Task<IEnumerable<SystemTask>> GetRunningSystemTasksAsync(int page = 1, int pageSize = 20)
        {
            return await _systemTaskRepository.GetByStatusPagedAsync("执行中", page, pageSize);
        }

        public async Task<IEnumerable<SystemTask>> GetCompletedSystemTasksAsync(int page = 1, int pageSize = 20)
        {
            return await _systemTaskRepository.GetByStatusPagedAsync("已完成", page, pageSize);
        }

        public async Task<IEnumerable<SystemTask>> GetFailedSystemTasksAsync(int page = 1, int pageSize = 20)
        {
            return await _systemTaskRepository.GetByStatusPagedAsync("失败", page, pageSize);
        }

        public async Task<SystemTask> CreateSystemTaskAsync(string name, string type, string? parameters = null, DateTime? scheduledAt = null)
        {
            var systemTask = new SystemTask
            {
                Id = Guid.NewGuid(),
                Name = name,
                Type = type,
                Parameters = parameters,
                Status = "待执行",
                ScheduledAt = scheduledAt,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _systemTaskRepository.AddAsync(systemTask);
            await _unitOfWork.SaveChangesAsync();

            return systemTask;
        }

        public async Task<SystemTask?> UpdateSystemTaskAsync(Guid id, string? name, string? type, string? parameters, DateTime? scheduledAt)
        {
            var systemTask = await _systemTaskRepository.GetByIdAsync(id);
            if (systemTask == null)
                return null;

            if (name != null) systemTask.Name = name;
            if (type != null) systemTask.Type = type;
            if (parameters != null) systemTask.Parameters = parameters;
            if (scheduledAt.HasValue) systemTask.ScheduledAt = scheduledAt;

            systemTask.UpdatedAt = DateTime.UtcNow;

            await _systemTaskRepository.UpdateAsync(systemTask);
            await _unitOfWork.SaveChangesAsync();

            return systemTask;
        }

        public async Task<bool> DeleteSystemTaskAsync(Guid id)
        {
            var systemTask = await _systemTaskRepository.GetByIdAsync(id);
            if (systemTask == null)
                return false;

            await _systemTaskRepository.DeleteAsync(systemTask);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<SystemTask?> StartSystemTaskAsync(Guid id)
        {
            var systemTask = await _systemTaskRepository.GetByIdAsync(id);
            if (systemTask == null)
                return null;

            systemTask.Status = "执行中";
            systemTask.StartedAt = DateTime.UtcNow;
            systemTask.UpdatedAt = DateTime.UtcNow;

            await _systemTaskRepository.UpdateAsync(systemTask);
            await _unitOfWork.SaveChangesAsync();

            return systemTask;
        }

        public async Task<SystemTask?> CompleteSystemTaskAsync(Guid id, string? result = null)
        {
            var systemTask = await _systemTaskRepository.GetByIdAsync(id);
            if (systemTask == null)
                return null;

            systemTask.Status = "已完成";
            systemTask.Result = result;
            systemTask.CompletedAt = DateTime.UtcNow;
            systemTask.UpdatedAt = DateTime.UtcNow;

            await _systemTaskRepository.UpdateAsync(systemTask);
            await _unitOfWork.SaveChangesAsync();

            return systemTask;
        }

        public async Task<SystemTask?> FailSystemTaskAsync(Guid id, string error)
        {
            var systemTask = await _systemTaskRepository.GetByIdAsync(id);
            if (systemTask == null)
                return null;

            systemTask.Status = "失败";
            systemTask.Error = error;
            systemTask.CompletedAt = DateTime.UtcNow;
            systemTask.UpdatedAt = DateTime.UtcNow;

            await _systemTaskRepository.UpdateAsync(systemTask);
            await _unitOfWork.SaveChangesAsync();

            return systemTask;
        }

        public async Task<SystemTask?> CancelSystemTaskAsync(Guid id)
        {
            var systemTask = await _systemTaskRepository.GetByIdAsync(id);
            if (systemTask == null)
                return null;

            systemTask.Status = "已取消";
            systemTask.UpdatedAt = DateTime.UtcNow;

            await _systemTaskRepository.UpdateAsync(systemTask);
            await _unitOfWork.SaveChangesAsync();

            return systemTask;
        }

        public async Task<Dictionary<string, object>> GetSystemTaskStatisticsAsync()
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-7);

            var tasks = await _systemTaskRepository.GetByDateRangeAsync(startDate, endDate);

            var statistics = new Dictionary<string, object>
            {
                ["TotalTasks"] = tasks.Count(),
                ["TasksByStatus"] = tasks.GroupBy(t => t.Status)
                                        .ToDictionary(g => g.Key, g => g.Count()),
                ["TasksByType"] = tasks.GroupBy(t => t.Type)
                                      .ToDictionary(g => g.Key, g => g.Count()),
                ["DailyTasks"] = tasks.GroupBy(t => t.CreatedAt.Date)
                                     .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count()),
                ["AverageExecutionTime"] = tasks.Where(t => t.StartedAt.HasValue && t.CompletedAt.HasValue)
                                               .Select(t => (t.CompletedAt.Value - t.StartedAt.Value).TotalSeconds)
                                               .DefaultIfEmpty(0)
                                               .Average()
            };

            return statistics;
        }
    }

    /// <summary>
    /// 系统版本服务实现
    /// </summary>
    public class SystemVersionService : ISystemVersionService
    {
        private readonly ISystemVersionRepository _systemVersionRepository;
        private readonly IUnitOfWork _unitOfWork;

        public SystemVersionService(ISystemVersionRepository systemVersionRepository, IUnitOfWork unitOfWork)
        {
            _systemVersionRepository = systemVersionRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<SystemVersion?> GetSystemVersionByIdAsync(Guid id)
        {
            return await _systemVersionRepository.GetByIdAsync(id);
        }

        public async Task<SystemVersion?> GetLatestSystemVersionAsync()
        {
            return await _systemVersionRepository.GetLatestVersionAsync();
        }

        public async Task<IEnumerable<SystemVersion>> GetAllSystemVersionsAsync()
        {
            return await _systemVersionRepository.GetAllAsync();
        }

        public async Task<SystemVersion> CreateSystemVersionAsync(string version, string description, string? downloadUrl = null, bool isForced = false)
        {
            var systemVersion = new SystemVersion
            {
                Id = Guid.NewGuid(),
                Version = version,
                Description = description,
                DownloadUrl = downloadUrl,
                IsForced = isForced,
                IsPublished = false,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _systemVersionRepository.AddAsync(systemVersion);
            await _unitOfWork.SaveChangesAsync();

            return systemVersion;
        }

        public async Task<SystemVersion?> UpdateSystemVersionAsync(Guid id, string? description, string? downloadUrl, bool? isForced)
        {
            var systemVersion = await _systemVersionRepository.GetByIdAsync(id);
            if (systemVersion == null)
                return null;

            if (description != null) systemVersion.Description = description;
            if (downloadUrl != null) systemVersion.DownloadUrl = downloadUrl;
            if (isForced.HasValue) systemVersion.IsForced = isForced.Value;

            systemVersion.UpdatedAt = DateTime.UtcNow;

            await _systemVersionRepository.UpdateAsync(systemVersion);
            await _unitOfWork.SaveChangesAsync();

            return systemVersion;
        }

        public async Task<bool> DeleteSystemVersionAsync(Guid id)
        {
            var systemVersion = await _systemVersionRepository.GetByIdAsync(id);
            if (systemVersion == null)
                return false;

            await _systemVersionRepository.DeleteAsync(systemVersion);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<SystemVersion?> PublishSystemVersionAsync(Guid id)
        {
            var systemVersion = await _systemVersionRepository.GetByIdAsync(id);
            if (systemVersion == null)
                return null;

            systemVersion.IsPublished = true;
            systemVersion.PublishedAt = DateTime.UtcNow;
            systemVersion.UpdatedAt = DateTime.UtcNow;

            await _systemVersionRepository.UpdateAsync(systemVersion);
            await _unitOfWork.SaveChangesAsync();

            return systemVersion;
        }

        public async Task<SystemVersion?> UnpublishSystemVersionAsync(Guid id)
        {
            var systemVersion = await _systemVersionRepository.GetByIdAsync(id);
            if (systemVersion == null)
                return null;

            systemVersion.IsPublished = false;
            systemVersion.UpdatedAt = DateTime.UtcNow;

            await _systemVersionRepository.UpdateAsync(systemVersion);
            await _unitOfWork.SaveChangesAsync();

            return systemVersion;
        }

        public async Task<bool> IsNewerSystemVersionAvailableAsync(string currentVersion)
        {
            var latestVersion = await _systemVersionRepository.GetLatestPublishedVersionAsync();
            if (latestVersion == null)
                return false;

            // 简单版本比较，实际项目中可能需要更复杂的版本比较逻辑
            return latestVersion.Version != currentVersion;
        }
    }

    /// <summary>
    /// 系统备份服务实现
    /// </summary>
    public class SystemBackupService : ISystemBackupService
    {
        private readonly ISystemBackupRepository _systemBackupRepository;
        private readonly IUnitOfWork _unitOfWork;

        public SystemBackupService(ISystemBackupRepository systemBackupRepository, IUnitOfWork unitOfWork)
        {
            _systemBackupRepository = systemBackupRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<SystemBackup?> GetSystemBackupByIdAsync(Guid id)
        {
            return await _systemBackupRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<SystemBackup>> GetAllSystemBackupsAsync()
        {
            return await _systemBackupRepository.GetAllAsync();
        }

        public async Task<SystemBackup> CreateSystemBackupAsync(string type, string? description = null)
        {
            var systemBackup = new SystemBackup
            {
                Id = Guid.NewGuid(),
                Type = type,
                Description = description,
                Status = "待执行",
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _systemBackupRepository.AddAsync(systemBackup);
            await _unitOfWork.SaveChangesAsync();

            return systemBackup;
        }

        public async Task<bool> DeleteSystemBackupAsync(Guid id)
        {
            var systemBackup = await _systemBackupRepository.GetByIdAsync(id);
            if (systemBackup == null)
                return false;

            await _systemBackupRepository.DeleteAsync(systemBackup);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<SystemBackup?> RestoreSystemBackupAsync(Guid id)
        {
            var systemBackup = await _systemBackupRepository.GetByIdAsync(id);
            if (systemBackup == null)
                return null;

            // 实际项目中，这里应该执行恢复逻辑
            systemBackup.Status = "已恢复";
            systemBackup.RestoredAt = DateTime.UtcNow;
            systemBackup.UpdatedAt = DateTime.UtcNow;

            await _systemBackupRepository.UpdateAsync(systemBackup);
            await _unitOfWork.SaveChangesAsync();

            return systemBackup;
        }

        public async Task<SystemBackup?> StartSystemBackupAsync(Guid id)
        {
            var systemBackup = await _systemBackupRepository.GetByIdAsync(id);
            if (systemBackup == null)
                return null;

            systemBackup.Status = "执行中";
            systemBackup.StartedAt = DateTime.UtcNow;
            systemBackup.UpdatedAt = DateTime.UtcNow;

            await _systemBackupRepository.UpdateAsync(systemBackup);
            await _unitOfWork.SaveChangesAsync();

            return systemBackup;
        }

        public async Task<SystemBackup?> CompleteSystemBackupAsync(Guid id, string? filePath = null)
        {
            var systemBackup = await _systemBackupRepository.GetByIdAsync(id);
            if (systemBackup == null)
                return null;

            systemBackup.Status = "已完成";
            systemBackup.FilePath = filePath;
            systemBackup.CompletedAt = DateTime.UtcNow;
            systemBackup.UpdatedAt = DateTime.UtcNow;

            await _systemBackupRepository.UpdateAsync(systemBackup);
            await _unitOfWork.SaveChangesAsync();

            return systemBackup;
        }

        public async Task<SystemBackup?> FailSystemBackupAsync(Guid id, string error)
        {
            var systemBackup = await _systemBackupRepository.GetByIdAsync(id);
            if (systemBackup == null)
                return null;

            systemBackup.Status = "失败";
            systemBackup.Error = error;
            systemBackup.CompletedAt = DateTime.UtcNow;
            systemBackup.UpdatedAt = DateTime.UtcNow;

            await _systemBackupRepository.UpdateAsync(systemBackup);
            await _unitOfWork.SaveChangesAsync();

            return systemBackup;
        }

        public async Task<bool> DeleteExpiredSystemBackupsAsync(int daysToKeep = 30)
        {
            var expiredDate = DateTime.UtcNow.AddDays(-daysToKeep);
            var backups = await _systemBackupRepository.GetByDateRangeAsync(DateTime.MinValue, expiredDate);

            foreach (var backup in backups)
            {
                await _systemBackupRepository.DeleteAsync(backup);
            }

            await _unitOfWork.SaveChangesAsync();
            return true;
        }

        public async Task<Dictionary<string, object>> GetSystemBackupStatisticsAsync()
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-30);

            var backups = await _systemBackupRepository.GetByDateRangeAsync(startDate, endDate);

            var statistics = new Dictionary<string, object>
            {
                ["TotalBackups"] = backups.Count(),
                ["BackupsByStatus"] = backups.GroupBy(b => b.Status)
                                           .ToDictionary(g => g.Key, g => g.Count()),
                ["BackupsByType"] = backups.GroupBy(b => b.Type)
                                         .ToDictionary(g => g.Key, g => g.Count()),
                ["DailyBackups"] = backups.GroupBy(b => b.CreatedAt.Date)
                                        .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count()),
                ["LastBackupTime"] = backups.OrderByDescending(b => b.CreatedAt)
                                           .Select(b => b.CreatedAt)
                                           .FirstOrDefault()
            };

            return statistics;
        }
    }

    /// <summary>
    /// 系统缓存服务实现
    /// </summary>
    public class SystemCacheService : ISystemCacheService
    {
        private readonly ISystemCacheRepository _systemCacheRepository;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IMemoryCache _memoryCache;

        public SystemCacheService(ISystemCacheRepository systemCacheRepository, IUnitOfWork unitOfWork, IMemoryCache memoryCache)
        {
            _systemCacheRepository = systemCacheRepository;
            _unitOfWork = unitOfWork;
            _memoryCache = memoryCache;
        }

        public async Task<SystemCache?> GetSystemCacheByIdAsync(Guid id)
        {
            return await _systemCacheRepository.GetByIdAsync(id);
        }

        public async Task<SystemCache?> GetSystemCacheByKeyAsync(string key)
        {
            return await _systemCacheRepository.GetByKeyAsync(key);
        }

        public async Task<IEnumerable<SystemCache>> GetAllSystemCachesAsync()
        {
            return await _systemCacheRepository.GetAllAsync();
        }

        public async Task<SystemCache> CreateSystemCacheAsync(string key, string value, int? expirationMinutes = null)
        {
            var systemCache = new SystemCache
            {
                Id = Guid.NewGuid(),
                Key = key,
                Value = value,
                ExpirationMinutes = expirationMinutes,
                ExpiresAt = expirationMinutes.HasValue ? DateTime.UtcNow.AddMinutes(expirationMinutes.Value) : null,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _systemCacheRepository.AddAsync(systemCache);
            await _unitOfWork.SaveChangesAsync();

            // 同时添加到内存缓存
            var cacheOptions = new MemoryCacheEntryOptions();
            if (expirationMinutes.HasValue)
            {
                cacheOptions.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(expirationMinutes.Value);
            }

            _memoryCache.Set(key, value, cacheOptions);

            return systemCache;
        }

        public async Task<SystemCache?> UpdateSystemCacheAsync(Guid id, string value, int? expirationMinutes = null)
        {
            var systemCache = await _systemCacheRepository.GetByIdAsync(id);
            if (systemCache == null)
                return null;

            systemCache.Value = value;
            systemCache.ExpirationMinutes = expirationMinutes;
            systemCache.ExpiresAt = expirationMinutes.HasValue ? DateTime.UtcNow.AddMinutes(expirationMinutes.Value) : null;
            systemCache.UpdatedAt = DateTime.UtcNow;

            await _systemCacheRepository.UpdateAsync(systemCache);
            await _unitOfWork.SaveChangesAsync();

            // 同时更新内存缓存
            var cacheOptions = new MemoryCacheEntryOptions();
            if (expirationMinutes.HasValue)
            {
                cacheOptions.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(expirationMinutes.Value);
            }

            _memoryCache.Set(systemCache.Key, value, cacheOptions);

            return systemCache;
        }

        public async Task<bool> DeleteSystemCacheAsync(Guid id)
        {
            var systemCache = await _systemCacheRepository.GetByIdAsync(id);
            if (systemCache == null)
                return false;

            await _systemCacheRepository.DeleteAsync(systemCache);
            await _unitOfWork.SaveChangesAsync();

            // 同时从内存缓存中删除
            _memoryCache.Remove(systemCache.Key);

            return true;
        }

        public async Task<bool> DeleteSystemCacheByKeyAsync(string key)
        {
            var systemCache = await _systemCacheRepository.GetByKeyAsync(key);
            if (systemCache == null)
                return false;

            await _systemCacheRepository.DeleteAsync(systemCache);
            await _unitOfWork.SaveChangesAsync();

            // 同时从内存缓存中删除
            _memoryCache.Remove(key);

            return true;
        }

        public async Task<bool> DeleteExpiredSystemCachesAsync()
        {
            var expiredCaches = await _systemCacheRepository.GetExpiredCachesAsync();
            foreach (var cache in expiredCaches)
            {
                await _systemCacheRepository.DeleteAsync(cache);
                // 同时从内存缓存中删除
                _memoryCache.Remove(cache.Key);
            }

            await _unitOfWork.SaveChangesAsync();
            return true;
        }

        public async Task<T?> GetSystemCacheValueAsync<T>(string key) where T : class
        {
            // 首先尝试从内存缓存获取
            if (_memoryCache.TryGetValue(key, out T? memoryValue))
            {
                return memoryValue;
            }

            // 如果内存缓存中没有，则从数据库获取
            var systemCache = await _systemCacheRepository.GetByKeyAsync(key);
            if (systemCache == null || (systemCache.ExpiresAt.HasValue && systemCache.ExpiresAt.Value < DateTime.UtcNow))
            {
                return null;
            }

            // 反序列化值
            try
            {
                var value = JsonSerializer.Deserialize<T>(systemCache.Value);
                if (value != null)
                {
                    // 添加到内存缓存
                    var cacheOptions = new MemoryCacheEntryOptions();
                    if (systemCache.ExpirationMinutes.HasValue)
                    {
                        cacheOptions.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(systemCache.ExpirationMinutes.Value);
                    }

                    _memoryCache.Set(key, value, cacheOptions);
                }

                return value;
            }
            catch
            {
                return null;
            }
        }

        public async Task<bool> SetSystemCacheValueAsync<T>(string key, T value, int? expirationMinutes = null) where T : class
        {
            try
            {
                var serializedValue = JsonSerializer.Serialize(value);

                // 检查是否已存在
                var systemCache = await _systemCacheRepository.GetByKeyAsync(key);
                if (systemCache != null)
                {
                    systemCache.Value = serializedValue;
                    systemCache.ExpirationMinutes = expirationMinutes;
                    systemCache.ExpiresAt = expirationMinutes.HasValue ? DateTime.UtcNow.AddMinutes(expirationMinutes.Value) : null;
                    systemCache.UpdatedAt = DateTime.UtcNow;

                    await _systemCacheRepository.UpdateAsync(systemCache);
                }
                else
                {
                    systemCache = new SystemCache
                    {
                        Id = Guid.NewGuid(),
                        Key = key,
                        Value = serializedValue,
                        ExpirationMinutes = expirationMinutes,
                        ExpiresAt = expirationMinutes.HasValue ? DateTime.UtcNow.AddMinutes(expirationMinutes.Value) : null,
                        CreatedAt = DateTime.UtcNow,
                        UpdatedAt = DateTime.UtcNow
                    };

                    await _systemCacheRepository.AddAsync(systemCache);
                }

                await _unitOfWork.SaveChangesAsync();

                // 同时添加到内存缓存
                var cacheOptions = new MemoryCacheEntryOptions();
                if (expirationMinutes.HasValue)
                {
                    cacheOptions.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(expirationMinutes.Value);
                }

                _memoryCache.Set(key, value, cacheOptions);

                return true;
            }
            catch
            {
                return false;
            }
        }

        public async Task<bool> RemoveSystemCacheValueAsync(string key)
        {
            return await DeleteSystemCacheByKeyAsync(key);
        }

        public async Task<bool> ClearAllSystemCacheAsync()
        {
            var caches = await _systemCacheRepository.GetAllAsync();
            foreach (var cache in caches)
            {
                await _systemCacheRepository.DeleteAsync(cache);
                // 同时从内存缓存中删除
                _memoryCache.Remove(cache.Key);
            }

            await _unitOfWork.SaveChangesAsync();
            return true;
        }

        public async Task<Dictionary<string, object>> GetSystemCacheStatisticsAsync()
        {
            var caches = await _systemCacheRepository.GetAllAsync();

            var statistics = new Dictionary<string, object>
            {
                ["TotalCaches"] = caches.Count(),
                ["ExpiredCaches"] = caches.Count(c => c.ExpiresAt.HasValue && c.ExpiresAt.Value < DateTime.UtcNow),
                ["MemoryCacheCount"] = _memoryCache.Count.ToString()
            };

            return statistics;
        }
    }

    /// <summary>
    /// 系统权限服务实现
    /// </summary>
    public class SystemPermissionService : ISystemPermissionService
    {
        private readonly ISystemPermissionRepository _systemPermissionRepository;
        private readonly IUserPermissionRepository _userPermissionRepository;
        private readonly IUnitOfWork _unitOfWork;

        public SystemPermissionService(
            ISystemPermissionRepository systemPermissionRepository,
            IUserPermissionRepository userPermissionRepository,
            IUnitOfWork unitOfWork)
        {
            _systemPermissionRepository = systemPermissionRepository;
            _userPermissionRepository = userPermissionRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<SystemPermission?> GetSystemPermissionByIdAsync(Guid id)
        {
            return await _systemPermissionRepository.GetByIdAsync(id);
        }

        public async Task<SystemPermission?> GetSystemPermissionByNameAsync(string name)
        {
            return await _systemPermissionRepository.GetByNameAsync(name);
        }

        public async Task<IEnumerable<SystemPermission>> GetAllSystemPermissionsAsync()
        {
            return await _systemPermissionRepository.GetAllAsync();
        }

        public async Task<SystemPermission> CreateSystemPermissionAsync(string name, string description, string? category = null)
        {
            var systemPermission = new SystemPermission
            {
                Id = Guid.NewGuid(),
                Name = name,
                Description = description,
                Category = category,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _systemPermissionRepository.AddAsync(systemPermission);
            await _unitOfWork.SaveChangesAsync();

            return systemPermission;
        }

        public async Task<SystemPermission?> UpdateSystemPermissionAsync(Guid id, string? description, string? category)
        {
            var systemPermission = await _systemPermissionRepository.GetByIdAsync(id);
            if (systemPermission == null)
                return null;

            if (description != null) systemPermission.Description = description;
            if (category != null) systemPermission.Category = category;

            systemPermission.UpdatedAt = DateTime.UtcNow;

            await _systemPermissionRepository.UpdateAsync(systemPermission);
            await _unitOfWork.SaveChangesAsync();

            return systemPermission;
        }

        public async Task<bool> DeleteSystemPermissionAsync(Guid id)
        {
            var systemPermission = await _systemPermissionRepository.GetByIdAsync(id);
            if (systemPermission == null)
                return false;

            await _systemPermissionRepository.DeleteAsync(systemPermission);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<IEnumerable<SystemPermission>> GetSystemPermissionsByCategoryAsync(string category)
        {
            return await _systemPermissionRepository.GetByCategoryAsync(category);
        }

        public async Task<bool> CheckUserHasPermissionAsync(Guid userId, string permissionName)
        {
            var permission = await _systemPermissionRepository.GetByNameAsync(permissionName);
            if (permission == null)
                return false;

            return await _userPermissionRepository.IsUserHasPermissionAsync(userId, permission.Id);
        }

        public async Task<IEnumerable<SystemPermission>> GetUserPermissionsAsync(Guid userId)
        {
            return await _userPermissionRepository.GetUserPermissionsAsync(userId);
        }

        public async Task<bool> GrantPermissionToUserAsync(Guid userId, Guid permissionId)
        {
            var isExists = await _userPermissionRepository.IsUserHasPermissionAsync(userId, permissionId);
            if (isExists)
                return true;

            var userPermission = new UserPermission
            {
                Id = Guid.NewGuid(),
                UserId = userId,
                PermissionId = permissionId,
                CreatedAt = DateTime.UtcNow
            };

            await _userPermissionRepository.AddAsync(userPermission);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> RevokePermissionFromUserAsync(Guid userId, Guid permissionId)
        {
            var userPermission = await _userPermissionRepository.GetUserPermissionAsync(userId, permissionId);
            if (userPermission == null)
                return false;

            await _userPermissionRepository.DeleteAsync(userPermission);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }
    }

    /// <summary>
    /// 系统角色服务实现
    /// </summary>
    public class SystemRoleService : ISystemRoleService
    {
        private readonly ISystemRoleRepository _systemRoleRepository;
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly IRolePermissionRepository _rolePermissionRepository;
        private readonly IUnitOfWork _unitOfWork;

        public SystemRoleService(
            ISystemRoleRepository systemRoleRepository,
            IUserRoleRepository userRoleRepository,
            IRolePermissionRepository rolePermissionRepository,
            IUnitOfWork unitOfWork)
        {
            _systemRoleRepository = systemRoleRepository;
            _userRoleRepository = userRoleRepository;
            _rolePermissionRepository = rolePermissionRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<SystemRole?> GetSystemRoleByIdAsync(Guid id)
        {
            return await _systemRoleRepository.GetByIdAsync(id);
        }

        public async Task<SystemRole?> GetSystemRoleByNameAsync(string name)
        {
            return await _systemRoleRepository.GetByNameAsync(name);
        }

        public async Task<IEnumerable<SystemRole>> GetAllSystemRolesAsync()
        {
            return await _systemRoleRepository.GetAllAsync();
        }

        public async Task<SystemRole> CreateSystemRoleAsync(string name, string description, int level = 0)
        {
            var systemRole = new SystemRole
            {
                Id = Guid.NewGuid(),
                Name = name,
                Description = description,
                Level = level,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _systemRoleRepository.AddAsync(systemRole);
            await _unitOfWork.SaveChangesAsync();

            return systemRole;
        }

        public async Task<SystemRole?> UpdateSystemRoleAsync(Guid id, string? description, int? level)
        {
            var systemRole = await _systemRoleRepository.GetByIdAsync(id);
            if (systemRole == null)
                return null;

            if (description != null) systemRole.Description = description;
            if (level.HasValue) systemRole.Level = level.Value;

            systemRole.UpdatedAt = DateTime.UtcNow;

            await _systemRoleRepository.UpdateAsync(systemRole);
            await _unitOfWork.SaveChangesAsync();

            return systemRole;
        }

        public async Task<bool> DeleteSystemRoleAsync(Guid id)
        {
            var systemRole = await _systemRoleRepository.GetByIdAsync(id);
            if (systemRole == null)
                return false;

            await _systemRoleRepository.DeleteAsync(systemRole);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> AssignRoleToUserAsync(Guid userId, Guid roleId)
        {
            var isExists = await _userRoleRepository.IsUserHasRoleAsync(userId, roleId);
            if (isExists)
                return true;

            var userRole = new UserRole
            {
                Id = Guid.NewGuid(),
                UserId = userId,
                RoleId = roleId,
                CreatedAt = DateTime.UtcNow
            };

            await _userRoleRepository.AddAsync(userRole);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> RemoveRoleFromUserAsync(Guid userId, Guid roleId)
        {
            var userRole = await _userRoleRepository.GetUserRoleAsync(userId, roleId);
            if (userRole == null)
                return false;

            await _userRoleRepository.DeleteAsync(userRole);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<IEnumerable<SystemRole>> GetUserRolesAsync(Guid userId)
        {
            return await _userRoleRepository.GetUserRolesAsync(userId);
        }

        public async Task<bool> GrantPermissionToRoleAsync(Guid roleId, Guid permissionId)
        {
            var isExists = await _rolePermissionRepository.IsRoleHasPermissionAsync(roleId, permissionId);
            if (isExists)
                return true;

            var rolePermission = new RolePermission
            {
                Id = Guid.NewGuid(),
                RoleId = roleId,
                PermissionId = permissionId,
                CreatedAt = DateTime.UtcNow
            };

            await _rolePermissionRepository.AddAsync(rolePermission);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> RevokePermissionFromRoleAsync(Guid roleId, Guid permissionId)
        {
            var rolePermission = await _rolePermissionRepository.GetRolePermissionAsync(roleId, permissionId);
            if (rolePermission == null)
                return false;

            await _rolePermissionRepository.DeleteAsync(rolePermission);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<IEnumerable<SystemPermission>> GetRolePermissionsAsync(Guid roleId)
        {
            return await _rolePermissionRepository.GetRolePermissionsAsync(roleId);
        }

        public async Task<bool> CheckUserHasRoleAsync(Guid userId, string roleName)
        {
            var role = await _systemRoleRepository.GetByNameAsync(roleName);
            if (role == null)
                return false;

            return await _userRoleRepository.IsUserHasRoleAsync(userId, role.Id);
        }
    }

    /// <summary>
    /// 系统用户服务实现
    /// </summary>
    public class SystemUserService : ISystemUserService
    {
        private readonly ISystemUserRepository _systemUserRepository;
        private readonly IUnitOfWork _unitOfWork;

        public SystemUserService(ISystemUserRepository systemUserRepository, IUnitOfWork unitOfWork)
        {
            _systemUserRepository = systemUserRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<SystemUser?> GetSystemUserByIdAsync(Guid id)
        {
            return await _systemUserRepository.GetByIdAsync(id);
        }

        public async Task<SystemUser?> GetSystemUserByUsernameAsync(string username)
        {
            return await _systemUserRepository.GetByUsernameAsync(username);
        }

        public async Task<SystemUser?> GetSystemUserByEmailAsync(string email)
        {
            return await _systemUserRepository.GetByEmailAsync(email);
        }

        public async Task<IEnumerable<SystemUser>> GetAllSystemUsersAsync(int page = 1, int pageSize = 20)
        {
            return await _systemUserRepository.GetAllPagedAsync(page, pageSize);
        }

        public async Task<SystemUser> CreateSystemUserAsync(string username, string email, string password, string? fullName = null, string? phoneNumber = null)
        {
            // 密码哈希处理
            var passwordHash = BCrypt.Net.BCrypt.HashPassword(password);

            var systemUser = new SystemUser
            {
                Id = Guid.NewGuid(),
                Username = username,
                Email = email,
                PasswordHash = passwordHash,
                FullName = fullName,
                PhoneNumber = phoneNumber,
                IsActive = true,
                IsEmailVerified = false,
                IsPhoneVerified = false,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _systemUserRepository.AddAsync(systemUser);
            await _unitOfWork.SaveChangesAsync();

            return systemUser;
        }

        public async Task<SystemUser?> UpdateSystemUserAsync(Guid id, string? email, string? fullName, string? phoneNumber)
        {
            var systemUser = await _systemUserRepository.GetByIdAsync(id);
            if (systemUser == null)
                return null;

            if (email != null) systemUser.Email = email;
            if (fullName != null) systemUser.FullName = fullName;
            if (phoneNumber != null) systemUser.PhoneNumber = phoneNumber;

            systemUser.UpdatedAt = DateTime.UtcNow;

            await _systemUserRepository.UpdateAsync(systemUser);
            await _unitOfWork.SaveChangesAsync();

            return systemUser;
        }

        public async Task<bool> DeleteSystemUserAsync(Guid id)
        {
            var systemUser = await _systemUserRepository.GetByIdAsync(id);
            if (systemUser == null)
                return false;

            await _systemUserRepository.DeleteAsync(systemUser);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> ChangeSystemUserPasswordAsync(Guid id, string oldPassword, string newPassword)
        {
            var systemUser = await _systemUserRepository.GetByIdAsync(id);
            if (systemUser == null)
                return false;

            // 验证旧密码
            if (!BCrypt.Net.BCrypt.Verify(oldPassword, systemUser.PasswordHash))
                return false;

            // 更新密码
            systemUser.PasswordHash = BCrypt.Net.BCrypt.HashPassword(newPassword);
            systemUser.UpdatedAt = DateTime.UtcNow;

            await _systemUserRepository.UpdateAsync(systemUser);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> ResetSystemUserPasswordAsync(Guid id, string newPassword)
        {
            var systemUser = await _systemUserRepository.GetByIdAsync(id);
            if (systemUser == null)
                return false;

            // 更新密码
            systemUser.PasswordHash = BCrypt.Net.BCrypt.HashPassword(newPassword);
            systemUser.UpdatedAt = DateTime.UtcNow;

            await _systemUserRepository.UpdateAsync(systemUser);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> LockSystemUserAsync(Guid id, string? reason = null)
        {
            var systemUser = await _systemUserRepository.GetByIdAsync(id);
            if (systemUser == null)
                return false;

            systemUser.IsLocked = true;
            systemUser.LockReason = reason;
            systemUser.LockedAt = DateTime.UtcNow;
            systemUser.UpdatedAt = DateTime.UtcNow;

            await _systemUserRepository.UpdateAsync(systemUser);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> UnlockSystemUserAsync(Guid id)
        {
            var systemUser = await _systemUserRepository.GetByIdAsync(id);
            if (systemUser == null)
                return false;

            systemUser.IsLocked = false;
            systemUser.LockReason = null;
            systemUser.LockedAt = null;
            systemUser.UpdatedAt = DateTime.UtcNow;

            await _systemUserRepository.UpdateAsync(systemUser);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> ActivateSystemUserAsync(Guid id)
        {
            var systemUser = await _systemUserRepository.GetByIdAsync(id);
            if (systemUser == null)
                return false;

            systemUser.IsActive = true;
            systemUser.UpdatedAt = DateTime.UtcNow;

            await _systemUserRepository.UpdateAsync(systemUser);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> DeactivateSystemUserAsync(Guid id)
        {
            var systemUser = await _systemUserRepository.GetByIdAsync(id);
            if (systemUser == null)
                return false;

            systemUser.IsActive = false;
            systemUser.UpdatedAt = DateTime.UtcNow;

            await _systemUserRepository.UpdateAsync(systemUser);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> VerifySystemUserEmailAsync(Guid id)
        {
            var systemUser = await _systemUserRepository.GetByIdAsync(id);
            if (systemUser == null)
                return false;

            systemUser.IsEmailVerified = true;
            systemUser.EmailVerifiedAt = DateTime.UtcNow;
            systemUser.UpdatedAt = DateTime.UtcNow;

            await _systemUserRepository.UpdateAsync(systemUser);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> VerifySystemUserPhoneAsync(Guid id)
        {
            var systemUser = await _systemUserRepository.GetByIdAsync(id);
            if (systemUser == null)
                return false;

            systemUser.IsPhoneVerified = true;
            systemUser.PhoneVerifiedAt = DateTime.UtcNow;
            systemUser.UpdatedAt = DateTime.UtcNow;

            await _systemUserRepository.UpdateAsync(systemUser);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<SystemUser?> UpdateSystemUserProfileAsync(Guid id, string? fullName, string? avatarUrl, string? bio)
        {
            var systemUser = await _systemUserRepository.GetByIdAsync(id);
            if (systemUser == null)
                return null;

            if (fullName != null) systemUser.FullName = fullName;
            if (avatarUrl != null) systemUser.AvatarUrl = avatarUrl;
            if (bio != null) systemUser.Bio = bio;

            systemUser.UpdatedAt = DateTime.UtcNow;

            await _systemUserRepository.UpdateAsync(systemUser);
            await _unitOfWork.SaveChangesAsync();

            return systemUser;
        }

        public async Task<Dictionary<string, object>> GetSystemUserStatisticsAsync()
        {
            var users = await _systemUserRepository.GetAllAsync();

            var statistics = new Dictionary<string, object>
            {
                ["TotalUsers"] = users.Count(),
                ["ActiveUsers"] = users.Count(u => u.IsActive),
                ["LockedUsers"] = users.Count(u => u.IsLocked),
                ["EmailVerifiedUsers"] = users.Count(u => u.IsEmailVerified),
                ["PhoneVerifiedUsers"] = users.Count(u => u.IsPhoneVerified),
                ["UsersCreatedToday"] = users.Count(u => u.CreatedAt.Date == DateTime.UtcNow.Date),
                ["UsersCreatedThisWeek"] = users.Count(u => u.CreatedAt >= DateTime.UtcNow.AddDays(-7)),
                ["UsersCreatedThisMonth"] = users.Count(u => u.CreatedAt >= DateTime.UtcNow.AddDays(-30))
            };

            return statistics;
        }
    }

    /// <summary>
    /// 系统菜单服务实现
    /// </summary>
    public class SystemMenuService : ISystemMenuService
    {
        private readonly ISystemMenuRepository _systemMenuRepository;
        private readonly IRoleMenuRepository _roleMenuRepository;
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly IUnitOfWork _unitOfWork;

        public SystemMenuService(
            ISystemMenuRepository systemMenuRepository,
            IRoleMenuRepository roleMenuRepository,
            IUserRoleRepository userRoleRepository,
            IUnitOfWork unitOfWork)
        {
            _systemMenuRepository = systemMenuRepository;
            _roleMenuRepository = roleMenuRepository;
            _userRoleRepository = userRoleRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<SystemMenu?> GetSystemMenuByIdAsync(Guid id)
        {
            return await _systemMenuRepository.GetByIdAsync(id);
        }

        public async Task<SystemMenu?> GetSystemMenuByCodeAsync(string code)
        {
            return await _systemMenuRepository.GetByCodeAsync(code);
        }

        public async Task<IEnumerable<SystemMenu>> GetAllSystemMenusAsync()
        {
            return await _systemMenuRepository.GetAllAsync();
        }

        public async Task<IEnumerable<SystemMenu>> GetSystemMenusByParentIdAsync(Guid? parentId)
        {
            return await _systemMenuRepository.GetByParentIdAsync(parentId);
        }

        public async Task<IEnumerable<SystemMenu>> GetUserSystemMenusAsync(Guid userId)
        {
            // 获取用户角色
            var userRoles = await _userRoleRepository.GetUserRolesAsync(userId);
            var roleIds = userRoles.Select(r => r.Id).ToList();

            // 获取角色菜单
            var roleMenus = await _roleMenuRepository.GetByRoleIdsAsync(roleIds);
            var menuIds = roleMenus.Select(m => m.MenuId).ToList();

            // 获取菜单
            var menus = await _systemMenuRepository.GetByIdsAsync(menuIds);
            return menus.OrderBy(m => m.Order);
        }

        public async Task<SystemMenu> CreateSystemMenuAsync(string name, string code, string url, int order = 0, Guid? parentId = null)
        {
            var systemMenu = new SystemMenu
            {
                Id = Guid.NewGuid(),
                Name = name,
                Code = code,
                Url = url,
                Order = order,
                ParentId = parentId,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _systemMenuRepository.AddAsync(systemMenu);
            await _unitOfWork.SaveChangesAsync();

            return systemMenu;
        }

        public async Task<SystemMenu?> UpdateSystemMenuAsync(Guid id, string? name, string? code, string? url, int? order, Guid? parentId)
        {
            var systemMenu = await _systemMenuRepository.GetByIdAsync(id);
            if (systemMenu == null)
                return null;

            if (name != null) systemMenu.Name = name;
            if (code != null) systemMenu.Code = code;
            if (url != null) systemMenu.Url = url;
            if (order.HasValue) systemMenu.Order = order.Value;
            if (parentId.HasValue) systemMenu.ParentId = parentId.Value;

            systemMenu.UpdatedAt = DateTime.UtcNow;

            await _systemMenuRepository.UpdateAsync(systemMenu);
            await _unitOfWork.SaveChangesAsync();

            return systemMenu;
        }

        public async Task<bool> DeleteSystemMenuAsync(Guid id)
        {
            var systemMenu = await _systemMenuRepository.GetByIdAsync(id);
            if (systemMenu == null)
                return false;

            await _systemMenuRepository.DeleteAsync(systemMenu);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> GrantMenuToRoleAsync(Guid roleId, Guid menuId)
        {
            var isExists = await _roleMenuRepository.IsRoleHasMenuAsync(roleId, menuId);
            if (isExists)
                return true;

            var roleMenu = new RoleMenu
            {
                Id = Guid.NewGuid(),
                RoleId = roleId,
                MenuId = menuId,
                CreatedAt = DateTime.UtcNow
            };

            await _roleMenuRepository.AddAsync(roleMenu);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> RevokeMenuFromRoleAsync(Guid roleId, Guid menuId)
        {
            var roleMenu = await _roleMenuRepository.GetRoleMenuAsync(roleId, menuId);
            if (roleMenu == null)
                return false;

            await _roleMenuRepository.DeleteAsync(roleMenu);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<IEnumerable<SystemMenu>> GetRoleMenusAsync(Guid roleId)
        {
            return await _roleMenuRepository.GetRoleMenusAsync(roleId);
        }

        public async Task<bool> CheckUserHasMenuAccessAsync(Guid userId, string menuCode)
        {
            var menu = await _systemMenuRepository.GetByCodeAsync(menuCode);
            if (menu == null)
                return false;

            // 获取用户角色
            var userRoles = await _userRoleRepository.GetUserRolesAsync(userId);
            var roleIds = userRoles.Select(r => r.Id).ToList();

            // 检查角色是否有菜单权限
            return await _roleMenuRepository.IsRoleHasMenuAsync(roleIds, menu.Id);
        }
    }

    /// <summary>
    /// 系统字典服务实现
    /// </summary>
    public class SystemDictionaryService : ISystemDictionaryService
    {
        private readonly ISystemDictionaryRepository _systemDictionaryRepository;
        private readonly IUnitOfWork _unitOfWork;

        public SystemDictionaryService(ISystemDictionaryRepository systemDictionaryRepository, IUnitOfWork unitOfWork)
        {
            _systemDictionaryRepository = systemDictionaryRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<SystemDictionary?> GetSystemDictionaryByIdAsync(Guid id)
        {
            return await _systemDictionaryRepository.GetByIdAsync(id);
        }

        public async Task<SystemDictionary?> GetSystemDictionaryByCodeAsync(string code)
        {
            return await _systemDictionaryRepository.GetByCodeAsync(code);
        }

        public async Task<IEnumerable<SystemDictionary>> GetAllSystemDictionariesAsync()
        {
            return await _systemDictionaryRepository.GetAllAsync();
        }

        public async Task<IEnumerable<SystemDictionary>> GetSystemDictionariesByCategoryAsync(string category)
        {
            return await _systemDictionaryRepository.GetByCategoryAsync(category);
        }

        public async Task<SystemDictionary> CreateSystemDictionaryAsync(string code, string name, string value, string? category = null, int order = 0)
        {
            var systemDictionary = new SystemDictionary
            {
                Id = Guid.NewGuid(),
                Code = code,
                Name = name,
                Value = value,
                Category = category,
                Order = order,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _systemDictionaryRepository.AddAsync(systemDictionary);
            await _unitOfWork.SaveChangesAsync();

            return systemDictionary;
        }

        public async Task<SystemDictionary?> UpdateSystemDictionaryAsync(Guid id, string? name, string? value, string? category, int? order)
        {
            var systemDictionary = await _systemDictionaryRepository.GetByIdAsync(id);
            if (systemDictionary == null)
                return null;

            if (name != null) systemDictionary.Name = name;
            if (value != null) systemDictionary.Value = value;
            if (category != null) systemDictionary.Category = category;
            if (order.HasValue) systemDictionary.Order = order.Value;

            systemDictionary.UpdatedAt = DateTime.UtcNow;

            await _systemDictionaryRepository.UpdateAsync(systemDictionary);
            await _unitOfWork.SaveChangesAsync();

            return systemDictionary;
        }

        public async Task<bool> DeleteSystemDictionaryAsync(Guid id)
        {
            var systemDictionary = await _systemDictionaryRepository.GetByIdAsync(id);
            if (systemDictionary == null)
                return false;

            await _systemDictionaryRepository.DeleteAsync(systemDictionary);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> DeleteSystemDictionariesByCategoryAsync(string category)
        {
            var dictionaries = await _systemDictionaryRepository.GetByCategoryAsync(category);
            foreach (var dictionary in dictionaries)
            {
                await _systemDictionaryRepository.DeleteAsync(dictionary);
            }

            await _unitOfWork.SaveChangesAsync();
            return true;
        }

        public async Task<Dictionary<string, string>> GetSystemDictionaryValuesByCategoryAsync(string category)
        {
            var dictionaries = await _systemDictionaryRepository.GetByCategoryAsync(category);
            return dictionaries.OrderBy(d => d.Order).ToDictionary(d => d.Code, d => d.Value);
        }

        public async Task<string?> GetSystemDictionaryValueByCodeAsync(string code)
        {
            var dictionary = await _systemDictionaryRepository.GetByCodeAsync(code);
            return dictionary?.Value;
        }
    }

    /// <summary>
    /// 系统区域服务实现
    /// </summary>
    public class SystemRegionService : ISystemRegionService
    {
        private readonly ISystemRegionRepository _systemRegionRepository;
        private readonly IUnitOfWork _unitOfWork;

        public SystemRegionService(ISystemRegionRepository systemRegionRepository, IUnitOfWork unitOfWork)
        {
            _systemRegionRepository = systemRegionRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<SystemRegion?> GetSystemRegionByIdAsync(Guid id)
        {
            return await _systemRegionRepository.GetByIdAsync(id);
        }

        public async Task<SystemRegion?> GetSystemRegionByCodeAsync(string code)
        {
            return await _systemRegionRepository.GetByCodeAsync(code);
        }

        public async Task<IEnumerable<SystemRegion>> GetAllSystemRegionsAsync()
        {
            return await _systemRegionRepository.GetAllAsync();
        }

        public async Task<IEnumerable<SystemRegion>> GetSystemRegionsByParentIdAsync(Guid? parentId)
        {
            return await _systemRegionRepository.GetByParentIdAsync(parentId);
        }

        public async Task<IEnumerable<SystemRegion>> GetSystemRegionsByLevelAsync(int level)
        {
            return await _systemRegionRepository.GetByLevelAsync(level);
        }

        public async Task<SystemRegion> CreateSystemRegionAsync(string name, string code, int level, Guid? parentId = null)
        {
            var systemRegion = new SystemRegion
            {
                Id = Guid.NewGuid(),
                Name = name,
                Code = code,
                Level = level,
                ParentId = parentId,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _systemRegionRepository.AddAsync(systemRegion);
            await _unitOfWork.SaveChangesAsync();

            return systemRegion;
        }

        public async Task<SystemRegion?> UpdateSystemRegionAsync(Guid id, string? name, string? code, int? level, Guid? parentId)
        {
            var systemRegion = await _systemRegionRepository.GetByIdAsync(id);
            if (systemRegion == null)
                return null;

            if (name != null) systemRegion.Name = name;
            if (code != null) systemRegion.Code = code;
            if (level.HasValue) systemRegion.Level = level.Value;
            if (parentId.HasValue) systemRegion.ParentId = parentId.Value;

            systemRegion.UpdatedAt = DateTime.UtcNow;

            await _systemRegionRepository.UpdateAsync(systemRegion);
            await _unitOfWork.SaveChangesAsync();

            return systemRegion;
        }

        public async Task<bool> DeleteSystemRegionAsync(Guid id)
        {
            var systemRegion = await _systemRegionRepository.GetByIdAsync(id);
            if (systemRegion == null)
                return false;

            await _systemRegionRepository.DeleteAsync(systemRegion);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<IEnumerable<SystemRegion>> GetSystemRegionPathAsync(Guid id)
        {
            var path = new List<SystemRegion>();
            var region = await _systemRegionRepository.GetByIdAsync(id);

            while (region != null)
            {
                path.Add(region);
                if (region.ParentId.HasValue)
                {
                    region = await _systemRegionRepository.GetByIdAsync(region.ParentId.Value);
                }
                else
                {
                    region = null;
                }
            }

            path.Reverse();
            return path;
        }

        public async Task<SystemRegion?> GetSystemRegionByNameAsync(string name)
        {
            return await _systemRegionRepository.GetByNameAsync(name);
        }

        public async Task<IEnumerable<SystemRegion>> SearchSystemRegionsAsync(string keyword)
        {
            return await _systemRegionRepository.SearchAsync(keyword);
        }
    }

    /// <summary>
    /// 系统消息模板服务实现
    /// </summary>
    public class SystemMessageTemplateService : ISystemMessageTemplateService
    {
        private readonly ISystemMessageTemplateRepository _systemMessageTemplateRepository;
        private readonly IUnitOfWork _unitOfWork;

        public SystemMessageTemplateService(ISystemMessageTemplateRepository systemMessageTemplateRepository, IUnitOfWork unitOfWork)
        {
            _systemMessageTemplateRepository = systemMessageTemplateRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<SystemMessageTemplate?> GetSystemMessageTemplateByIdAsync(Guid id)
        {
            return await _systemMessageTemplateRepository.GetByIdAsync(id);
        }

        public async Task<SystemMessageTemplate?> GetSystemMessageTemplateByCodeAsync(string code)
        {
            return await _systemMessageTemplateRepository.GetByCodeAsync(code);
        }

        public async Task<IEnumerable<SystemMessageTemplate>> GetAllSystemMessageTemplatesAsync()
        {
            return await _systemMessageTemplateRepository.GetAllAsync();
        }

        public async Task<IEnumerable<SystemMessageTemplate>> GetSystemMessageTemplatesByTypeAsync(string type)
        {
            return await _systemMessageTemplateRepository.GetByTypeAsync(type);
        }

        public async Task<SystemMessageTemplate> CreateSystemMessageTemplateAsync(string code, string name, string type, string title, string content)
        {
            var systemMessageTemplate = new SystemMessageTemplate
            {
                Id = Guid.NewGuid(),
                Code = code,
                Name = name,
                Type = type,
                Title = title,
                Content = content,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _systemMessageTemplateRepository.AddAsync(systemMessageTemplate);
            await _unitOfWork.SaveChangesAsync();

            return systemMessageTemplate;
        }

        public async Task<SystemMessageTemplate?> UpdateSystemMessageTemplateAsync(Guid id, string? name, string? type, string? title, string? content)
        {
            var systemMessageTemplate = await _systemMessageTemplateRepository.GetByIdAsync(id);
            if (systemMessageTemplate == null)
                return null;

            if (name != null) systemMessageTemplate.Name = name;
            if (type != null) systemMessageTemplate.Type = type;
            if (title != null) systemMessageTemplate.Title = title;
            if (content != null) systemMessageTemplate.Content = content;

            systemMessageTemplate.UpdatedAt = DateTime.UtcNow;

            await _systemMessageTemplateRepository.UpdateAsync(systemMessageTemplate);
            await _unitOfWork.SaveChangesAsync();

            return systemMessageTemplate;
        }

        public async Task<bool> DeleteSystemMessageTemplateAsync(Guid id)
        {
            var systemMessageTemplate = await _systemMessageTemplateRepository.GetByIdAsync(id);
            if (systemMessageTemplate == null)
                return false;

            await _systemMessageTemplateRepository.DeleteAsync(systemMessageTemplate);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<string> RenderSystemMessageTemplateAsync(Guid id, Dictionary<string, object> parameters)
        {
            var template = await _systemMessageTemplateRepository.GetByIdAsync(id);
            if (template == null)
                return string.Empty;

            return RenderTemplate(template.Content, parameters);
        }

        public async Task<string> RenderSystemMessageTemplateByCodeAsync(string code, Dictionary<string, object> parameters)
        {
            var template = await _systemMessageTemplateRepository.GetByCodeAsync(code);
            if (template == null)
                return string.Empty;

            return RenderTemplate(template.Content, parameters);
        }

        public async Task<bool> SendSystemMessageByTemplateAsync(Guid userId, string templateCode, Dictionary<string, object> parameters)
        {
            var template = await _systemMessageTemplateRepository.GetByCodeAsync(templateCode);
            if (template == null)
                return false;

            var title = RenderTemplate(template.Title, parameters);
            var content = RenderTemplate(template.Content, parameters);

            // 这里应该调用消息发送服务，实际项目中需要实现
            // 例如：await _messageService.SendMessageAsync(userId, title, content);

            return true;
        }

        private string RenderTemplate(string template, Dictionary<string, object> parameters)
        {
            foreach (var parameter in parameters)
            {
                template = template.Replace($"{{{parameter.Key}}}", parameter.Value?.ToString() ?? string.Empty);
            }

            return template;
        }
    }

    /// <summary>
    /// 系统统计服务实现
    /// </summary>
    public class SystemStatisticsService : ISystemStatisticsService
    {
        private readonly ISystemUserRepository _systemUserRepository;
        private readonly ISystemLogRepository _systemLogRepository;
        private readonly ISystemTaskRepository _systemTaskRepository;
        private readonly ISystemBackupRepository _systemBackupRepository;
        private readonly ISystemCacheRepository _systemCacheRepository;

        public SystemStatisticsService(
            ISystemUserRepository systemUserRepository,
            ISystemLogRepository systemLogRepository,
            ISystemTaskRepository systemTaskRepository,
            ISystemBackupRepository systemBackupRepository,
            ISystemCacheRepository systemCacheRepository)
        {
            _systemUserRepository = systemUserRepository;
            _systemLogRepository = systemLogRepository;
            _systemTaskRepository = systemTaskRepository;
            _systemBackupRepository = systemBackupRepository;
            _systemCacheRepository = systemCacheRepository;
        }

        public async Task<Dictionary<string, object>> GetSystemOverviewStatisticsAsync()
        {
            var totalUsers = await _systemUserRepository.GetTotalCountAsync();
            var activeUsers = await _systemUserRepository.GetActiveCountAsync();
            var recentLogs = await _systemLogRepository.GetByDateRangeAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow);
            var pendingTasks = await _systemTaskRepository.GetByStatusAsync("待执行");
            var failedTasks = await _systemTaskRepository.GetByStatusAsync("失败");

            var statistics = new Dictionary<string, object>
            {
                ["TotalUsers"] = totalUsers,
                ["ActiveUsers"] = activeUsers,
                ["RecentLogs"] = recentLogs.Count(),
                ["PendingTasks"] = pendingTasks.Count(),
                ["FailedTasks"] = failedTasks.Count()
            };

            return statistics;
        }

        public async Task<Dictionary<string, object>> GetUserStatisticsAsync(int days = 30)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-days);

            var users = await _systemUserRepository.GetByDateRangeAsync(startDate, endDate);
            var activeUsers = await _systemUserRepository.GetActiveByDateRangeAsync(startDate, endDate);

            var statistics = new Dictionary<string, object>
            {
                ["NewUsers"] = users.Count(),
                ["ActiveUsers"] = activeUsers.Count(),
                ["DailyNewUsers"] = users.GroupBy(u => u.CreatedAt.Date)
                                        .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count()),
                ["DailyActiveUsers"] = activeUsers.GroupBy(u => u.CreatedAt.Date)
                                                 .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count())
            };

            return statistics;
        }

        public async Task<Dictionary<string, object>> GetSystemPerformanceStatisticsAsync(int hours = 24)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddHours(-hours);

            var errorLogs = await _systemLogRepository.GetByLevelAndDateRangeAsync("Error", startDate, endDate);
            var warningLogs = await _systemLogRepository.GetByLevelAndDateRangeAsync("Warning", startDate, endDate);

            var statistics = new Dictionary<string, object>
            {
                ["ErrorLogs"] = errorLogs.Count(),
                ["WarningLogs"] = warningLogs.Count(),
                ["HourlyErrorLogs"] = errorLogs.GroupBy(l => l.CreatedAt.Hour)
                                             .ToDictionary(g => g.Key.ToString(), g => g.Count()),
                ["HourlyWarningLogs"] = warningLogs.GroupBy(l => l.CreatedAt.Hour)
                                               .ToDictionary(g => g.Key.ToString(), g => g.Count())
            };

            return statistics;
        }

        public async Task<Dictionary<string, object>> GetSystemErrorStatisticsAsync(int days = 7)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-days);

            var errorLogs = await _systemLogRepository.GetByLevelAndDateRangeAsync("Error", startDate, endDate);

            var statistics = new Dictionary<string, object>
            {
                ["TotalErrors"] = errorLogs.Count(),
                ["ErrorsByCategory"] = errorLogs.GroupBy(l => l.Category)
                                              .ToDictionary(g => g.Key, g => g.Count()),
                ["DailyErrors"] = errorLogs.GroupBy(l => l.CreatedAt.Date)
                                         .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count())
            };

            return statistics;
        }

        public async Task<Dictionary<string, object>> GetSystemUsageStatisticsAsync(int days = 30)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-days);

            var logs = await _systemLogRepository.GetByDateRangeAsync(startDate, endDate);

            var statistics = new Dictionary<string, object>
            {
                ["TotalLogs"] = logs.Count(),
                ["LogsByCategory"] = logs.GroupBy(l => l.Category)
                                       .ToDictionary(g => g.Key, g => g.Count()),
                ["DailyLogs"] = logs.GroupBy(l => l.CreatedAt.Date)
                                   .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count())
            };

            return statistics;
        }

        public async Task<Dictionary<string, object>> GetSystemDatabaseStatisticsAsync()
        {
            // 这里应该返回数据库统计信息，实际项目中需要实现
            var statistics = new Dictionary<string, object>
            {
                ["DatabaseSize"] = "需要实现",
                ["TableCount"] = "需要实现",
                ["IndexCount"] = "需要实现"
            };

            return statistics;
        }

        public async Task<Dictionary<string, object>> GetSystemCacheStatisticsAsync()
        {
            var caches = await _systemCacheRepository.GetAllAsync();
            var expiredCaches = await _systemCacheRepository.GetExpiredCachesAsync();

            var statistics = new Dictionary<string, object>
            {
                ["TotalCaches"] = caches.Count(),
                ["ExpiredCaches"] = expiredCaches.Count(),
                ["CachesByCategory"] = caches.GroupBy(c => c.Category)
                                           .ToDictionary(g => g.Key, g => g.Count())
            };

            return statistics;
        }

        public async Task<Dictionary<string, object>> GetSystemStorageStatisticsAsync()
        {
            // 这里应该返回存储统计信息，实际项目中需要实现
            var statistics = new Dictionary<string, object>
            {
                ["TotalStorage"] = "需要实现",
                ["UsedStorage"] = "需要实现",
                ["FreeStorage"] = "需要实现"
            };

            return statistics;
        }

        public async Task<Dictionary<string, object>> GetSystemApiStatisticsAsync(int days = 7)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-days);

            var apiLogs = await _systemLogRepository.GetByCategoryAndDateRangeAsync("API", startDate, endDate);

            var statistics = new Dictionary<string, object>
            {
                ["TotalApiCalls"] = apiLogs.Count(),
                ["ApiCallsByEndpoint"] = apiLogs.GroupBy(l => l.Message)
                                              .ToDictionary(g => g.Key, g => g.Count()),
                ["DailyApiCalls"] = apiLogs.GroupBy(l => l.CreatedAt.Date)
                                         .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count())
            };

            return statistics;
        }
    }
}